// 导入路由模块
import Vue from 'vue'
import VueRouter from 'vue-router'

//导入自定义模块
import NotFound from '@/components/404'
import Header from '@/components/header'

import Home from '@/views/home'
import HomeIndex from '@/views/home/index'


/*Router Modules */
import monitorRouter from '@/router/modules/monitor'
import statisRouter from '@/router/modules/statis'
import SystemRouter from '@/router/modules/system'
import AffairRouter from '@/router/modules/affair'
import manageRouter from '@/router/modules/manage'
import $storage from '@/api/localStorageData.js'

//使用路由
Vue.use(VueRouter)
Vue.use($storage)
//注册路由器
let router=new VueRouter({
  mode: 'history',
  routes:[
    {
      path:'/login',
      name:'login',
      component:()=>import('@/views/admin/login.vue'),
    },
    { /*信息总览*/
      path:'/',
      name:'home',
      component:Home,
      redirect:'/index',
      children:[
        {path:'index',
        components:{top:Header, default:HomeIndex},
        meta: { requiresAuth: true }
      },
      ]
    },
    monitorRouter,
    AffairRouter,  
    manageRouter,
    SystemRouter,
    statisRouter,
    {path:'*',component:NotFound},
  ]
})
// 全局路由守卫
router.beforeEach((to,from,next)=>{
  let nowDate=new Date().getTime()
  let exp=30*60*1000
  let autoToken=localStorage.getItem('authToken')
  // 判断是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    //判断autoToken是否存在
    if(autoToken===null || !autoToken){
      next({
        path: '/login',
        query: {redirect: to.fullPath}
        }) 
    }else{
      autoToken=JSON.parse(localStorage.getItem('authToken'))
      if(nowDate-autoToken.time < exp){
        //未过期
        next()
      }else{
        //console.log('localStorage到期!')
        localStorage.removeItem('user')
        localStorage.removeItem('authToken')
        next({
          path: '/login',
          query: {redirect: to.fullPath}
          })
      }
    }
  } else {
  next()
  }
})
export default router